package com.spark.trouble.handle

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.spark.common.App
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.alert
import com.spark.common.ext.report
import com.spark.common.ext.wrapIO
import com.spark.common.model.db.TroubleLocationModel
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.trouble.R
import io.objectbox.Box
import kotlinx.android.synthetic.main.frag_trouble_location.*
import me.yokeyword.fragmentation.SupportActivity

/**
 * 隐患位置
 */
class TroubleSpotFragment : BaseFragment() {
    private lateinit var troubleLocationAdapter: TroubleLocationAdapter
    private var troubleLocationBox: Box<TroubleLocationModel>? = App.boxStore.boxFor(TroubleLocationModel::class.java)

    companion object {
        val resSpot = 0x888
        fun newInstance(): TroubleSpotFragment {
            return TroubleSpotFragment()
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_trouble_location
    }

    @SuppressLint("CheckResult")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        iv_back.setOnClickListener { pop() }
        tv_title.text = "隐患位置"

        fetchHistoryLocation()

        troubleLocationAdapter = TroubleLocationAdapter(R.layout.item_trouble_location).apply {
            setOnItemChildClickListener { _, _, position ->
                val model = troubleLocationAdapter.data[position]
                et_location.setText(model.location)
            }
            setOnItemClickListener { _, _, position ->
                val model = troubleLocationAdapter.data[position]
                et_location.setText(model.location)
                updateCheckState(position)
            }
        }
        recy_trouble_locations.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = troubleLocationAdapter
        }

        btn_save.setOnClickListener {
            val location = et_location.text.toString().trim()
            if (location.isNullOrBlank()) {
                alert("请输入隐患位置")
            } else {
                troubleLocationAdapter.addData(TroubleLocationModel(location = location))
                val bundle = Bundle()
                bundle.putString("location", location)
                setFragmentResult(resSpot, bundle)
                activity?.let { it as SupportActivity }?.pop()
                /*troubleLocationBox?.apply {
                    val similarValues = query().equal(TroubleLocationModel_.location, location).build().find()
                    remove(similarValues)
                    put(TroubleLocationModel(location = location))
                    val bundle = Bundle()
                    bundle.putString("location", location)
                    setFragmentResult(resSpot, bundle)
                    activity?.let { it as SupportActivity }?.pop()
                }*/
            }
        }

        /*RxQuery.observable(troubleLocationBox?.query()?.build())
                .wrapCompute()
                .subscribe(
                        {
                            it.forEach {
                                it.isChecked = false
                            }
                            it.reverse()
                            troubleLocationAdapter.addData(it)
                        },
                        {
                            it.printStackTrace()
                            report(it)
                        },
                        {},
                        {}
                )*/
    }

    @SuppressLint("CheckResult")
    private fun fetchHistoryLocation() {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_fetch_history_location}", "{}".toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, HistoryLocationModel::class.java)?.apply {
                                if (code == "200") {
                                    if (resultMaps.isNotEmpty()) {
                                        val locations = mutableListOf<TroubleLocationModel>()
                                        resultMaps[0].locationhistory.forEach {
                                            locations.add(it.toTroubleLocationModel())
                                        }
                                        troubleLocationAdapter.addData(locations)
                                    }
                                }
                            }
                        },
                        {
                            hideLoader()
                            it.printStackTrace()
                            report(it)
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading()
                        }
                )
    }
}

/**
 * 历史位置
 */
class TroubleLocationAdapter(layoutRes: Int) : BaseQuickAdapter<TroubleLocationModel, BaseViewHolder>(layoutRes) {
    override fun convert(helper: BaseViewHolder?, item: TroubleLocationModel?) {
        helper?.apply {
            getView<TextView>(R.id.tv_location).apply {
                text = item?.location
                setTextColor(if (item?.isChecked == true) mContext.resources.getColor(R.color.color_4b86b1) else mContext.resources.getColor(R.color.color666))
            }
            getView<ImageView>(R.id.iv_arr).setOnClickListener {
                onItemChildClickListener?.onItemChildClick(this@TroubleLocationAdapter, it, adapterPosition)
                updateCheckState(adapterPosition)
            }
            itemView.setBackgroundResource(if (item?.isChecked == true) R.drawable.bg_round_rect_dfefeed else R.drawable.bg_round_rect_eee)
        }
    }

    fun updateCheckState(position: Int) {
        data.forEachIndexed { i, data ->
            data.isChecked = i == position
        }
        notifyDataSetChanged()
    }

}


data class HistoryLocationModel(
        var msg: String = "", // 成功
        var code: String = "", // 200
        var data: Any = Any(), // null
        var resultMaps: List<ResultMap> = listOf()
) {

    data class ResultMap(
            var locationhistory: List<Locationhistory> = listOf()
    ) {

        data class Locationhistory(
                var id: Int = 0, // 51
                var location: String = "", // 隐患再来一次
                var timestamp: Long = 0, // 1532555219000
                var sysuserId: Int = 0 // 19
        ) {
            fun toTroubleLocationModel(): TroubleLocationModel {
                return TroubleLocationModel(id = this.id.toString(), location = this.location)
            }
        }

    }

}